package com.bf.electroplating.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bf.electroplating.mapper.CompanyDeviceRelationMapper;
import com.bf.electroplating.pojo.entity.CompanyDeviceRelation;
import com.bf.electroplating.pojo.vo.DeviceRelationVO;
import com.bf.electroplating.service.ICompanyDeviceRelationService;
import java.util.UUID;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 企业设备关联关系表 服务实现类
 * </p>
 *
 * @author gzd
 * @since 2025-01-15
 */
@Service
public class CompanyDeviceRelationServiceImpl extends ServiceImpl<CompanyDeviceRelationMapper, CompanyDeviceRelation> 
        implements ICompanyDeviceRelationService {

    @Autowired
    private CompanyDeviceRelationMapper companyDeviceRelationMapper;

    @Override
    public List<DeviceRelationVO> getDeviceRelationsByEnterpriseId(String enterpriseId) {
        // 获取车间和监控点信息
        List<DeviceRelationVO> workshopList = companyDeviceRelationMapper.getDeviceRelationsByEnterpriseId(enterpriseId);
        
        // 为每个车间构建设备关联信息
        for (DeviceRelationVO workshop : workshopList) {
            List<DeviceRelationVO.DeviceVO> deviceList = buildDeviceList(enterpriseId, workshop.getWorkshopName());
            workshop.setDeviceList(deviceList);
        }
        
        return workshopList;
    }
    
    /**
     * 构建设备列表及其关联的治理设备
     */
    private List<DeviceRelationVO.DeviceVO> buildDeviceList(String enterpriseId, String workshopName) {
        // 这里需要根据实际业务逻辑来构建设备关联关系
        // 暂时返回空列表，实际实现时需要查询设备表和关联关系表
        return new ArrayList<>();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void syncDeviceRelations(String enterpriseId, List<DeviceRelationVO> deviceRelations) {
        if (deviceRelations == null || deviceRelations.isEmpty()) {
            // 如果没有关联数据，则删除该企业的所有设备关联关系
            deleteByCompanyId(enterpriseId);
            return;
        }

        // 获取该企业现有的设备关联关系
        List<CompanyDeviceRelation> existingRelations = this.lambdaQuery()
                .eq(CompanyDeviceRelation::getCompanyId, enterpriseId)
                .eq(CompanyDeviceRelation::getDelFlag, "0")
                .list();

        List<CompanyDeviceRelation> relationsToInsert = new ArrayList<>();
        List<CompanyDeviceRelation> relationsToUpdate = new ArrayList<>();
        List<String> processedRelationIds = new ArrayList<>();
        
        for (DeviceRelationVO deviceRelation : deviceRelations) {
            if (deviceRelation.getDeviceList() != null) {
                for (DeviceRelationVO.DeviceVO device : deviceRelation.getDeviceList()) {
                    if (device.getGovernanceSiteVOList() != null) {
                        for (DeviceRelationVO.GovernanceSiteVO governanceSite : device.getGovernanceSiteVOList()) {
                            String productionDeviceId = device.getId().toString();
                            String governanceDeviceId = governanceSite.getGovernanceId().toString();
                            
                            // 查找是否已存在相同的关联关系
                            CompanyDeviceRelation existingRelation = existingRelations.stream()
                                    .filter(r -> productionDeviceId.equals(r.getProductionDeviceId()) 
                                            && governanceDeviceId.equals(r.getGovernanceDeviceId()))
                                    .findFirst()
                                    .orElse(null);
                            
                            if (existingRelation != null) {
                                // 更新现有关联关系
                                existingRelation.setHostStandbyType(governanceSite.getHostStandbyType());
                                existingRelation.setRelationType("01");
                                existingRelation.setUpdateBy("system");
                                existingRelation.setUpdateTime(LocalDateTime.now());
                                relationsToUpdate.add(existingRelation);
                                processedRelationIds.add(existingRelation.getId());
                            } else {
                                // 新增关联关系
                                CompanyDeviceRelation newRelation = new CompanyDeviceRelation();
                                newRelation.setId(UUID.randomUUID().toString().replace("-", ""));
                                newRelation.setProductionDeviceId(productionDeviceId);
                                newRelation.setGovernanceDeviceId(governanceDeviceId);
                                newRelation.setHostStandbyType(governanceSite.getHostStandbyType());
                                newRelation.setRelationType("01"); // 生产-治理关联
                                newRelation.setCompanyId(enterpriseId);
                                newRelation.setCreateBy("system");
                                newRelation.setParkId("1001");
                                newRelation.setCreateTime(LocalDateTime.now());
                                newRelation.setDelFlag("0");
                                relationsToInsert.add(newRelation);
                            }
                        }
                    }
                }
            }
        }
        
        // 批量更新现有关联关系
        if (!relationsToUpdate.isEmpty()) {
            this.updateBatchById(relationsToUpdate);
        }
        
        // 批量插入新关联关系
        if (!relationsToInsert.isEmpty()) {
            companyDeviceRelationMapper.batchInsert(relationsToInsert);
        }
        
        // 删除不再存在的关联关系（逻辑删除）
        List<CompanyDeviceRelation> relationsToDelete = existingRelations.stream()
                .filter(r -> !processedRelationIds.contains(r.getId()))
                .collect(Collectors.toList());
        
        if (!relationsToDelete.isEmpty()) {
            for (CompanyDeviceRelation relation : relationsToDelete) {
                relation.setDelFlag("1");
                relation.setUpdateBy("system");
                relation.setUpdateTime(LocalDateTime.now());
            }
            this.updateBatchById(relationsToDelete);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteByCompanyId(String companyId) {
        companyDeviceRelationMapper.deleteByCompanyId(companyId);
    }
}
